package com.marco.commons;

import com.google.common.collect.Lists;
import org.dozer.DozerBeanMapper;

import java.util.Collection;
import java.util.List;

/**
 * BeanMapper.java
 * created on 2016/6/17 17:11
 * copyright(c) 2016 All Rights Reserved
 * contact with mkxiao@live.com
 * 封装常用的dozer转换Bean对象常用的几种方式,根据不同配置的DozerMapper简单封装dozer
 */
public class BeanMapper {
    private static DozerBeanMapper dozer = new DozerBeanMapper();
    // source中时间格式为yyyy-MM-dd
    public static DozerBeanMapper dateDozer = new DozerBeanMapper(Lists.newArrayList("dozer/date.xml"));
    // source中时间格式为yyyy-MM-dd HH:mm:ss
    public static DozerBeanMapper datetimeDozer = new DozerBeanMapper(Lists.newArrayList("dozer/datetime.xml"));
    // 将非空字段赋值给对象
    public static DozerBeanMapper notNullDozer = new DozerBeanMapper(Lists.newArrayList("dozer/not-map-null.xml"));

    /**
     * 基于Dozer转换对象的类型.
     */
    public static <T> T map(Object source, Class<T> destinationClass) {
        return dozer.map(source, destinationClass);
    }

    /**
     *根据配置的dozer进行对象转换
     */
    public static <T> T map(DozerBeanMapper dozer, Object source, Class<T> destinationClass) {
        return dozer.map(source, destinationClass);
    }
    /**
     * 基于dozer转换集合
     */
    public static <T> List<T> mapList(Collection sourceList, Class<T> destinationClass) {
        List<T> destinationList = Lists.newArrayList();
        for (Object sourceObject : sourceList) {
            T destinationObject = dozer.map(sourceObject, destinationClass);
            destinationList.add(destinationObject);
        }
        return destinationList;
    }
    /**
     * 基于配置的dozer转换集合
     */
    public static <T> List<T> mapList(DozerBeanMapper dozer, Collection sourceList, Class<T> destinationClass) {
        List<T> destinationList = Lists.newArrayList();
        for (Object sourceObject : sourceList) {
            T destinationObject = dozer.map(sourceObject, destinationClass);
            destinationList.add(destinationObject);
        }
        return destinationList;
    }
    /**
     * 基于dozer进行拷贝
     */
    public static void copy(Object source, Object destinationObject) {
        dozer.map(source, destinationObject);
    }
    /**
     * 基于配置的dozer进行拷贝
     */
    public static void copy(DozerBeanMapper dozer, Object source, Object destinationObject) {
        dozer.map(source, destinationObject);
    }

}
